package com.dl.ycq.framework.datasource.aspect;

import com.dl.ycq.framework.datasource.annotation.DataSource;
import com.dl.ycq.framework.datasource.bean.DynamicDataSource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class DataSourceAspect implements Ordered {

    private Logger log = LoggerFactory.getLogger(DataSourceAspect.class);

    /**
     * 切点: 所有配置 DataSource 注解的方法
     */
    @Pointcut("@annotation(com.dl.ycq.framework.datasource.annotation.DataSource)")
    public void dataSourcePointCut() {
    }

    @Around(value = "dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        Object result;
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DataSource ds = method.getAnnotation(DataSource.class);
        // 通过判断 DataSource 中的值来判断当前方法应用哪个数据源
        DynamicDataSource.setDataSource(ds.value().getDataSourceName());
        // log.info("当前数据源: {}", ds.value());
        // log.debug("set datasource is {}", ds.value());
        try {
            result = point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
            // log.debug("clean datasource");
        }
        return result;
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
